<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { IDS } from '#/api/common';
import type { EmployeeVO } from '#/api/company/audience/model';

import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { AccessControl, useAccess } from '@vben/access';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { useUserStore } from '@vben/stores';

import {
  Dropdown,
  Menu,
  MenuItem,
  // Popconfirm,
  message,
  Space,
  Tag,
  Tooltip,
} from 'ant-design-vue';

import {
  useVbenVxeGrid,
  vxeCheckboxChecked,
  vxeCheckboxCheckedCount,
} from '#/adapter/vxe-table';
import {
  employeeBatchSetTags,
  employeeDownloadImportTemplate,
  employeeEmailMatch,
  employeeImport,
  employeeMobileMatch,
  employeePage,
  employeeTagMatch,
} from '#/api/company/audience';
import { personalFavoriteAddMemberBySearch } from '#/api/company/favorite/personal';
// import { getVxePopupContainer } from '@vben/utils';
// import { useClinkCall } from '#/components/clink/src/useClink';
import { useAdvancedFilter } from '#/components/advanced-filter';
// import { Clink } from '#/components/clink';
import Clink from '#/components/clink/src/btn.vue';
import { useClinkCall } from '#/components/clink/src/useClinkNew';
import addEmployeeToFavoriteModal from '#/components/favorite/src/add-employee-modal.vue';
import importModal from '#/components/import/src/import-modal.vue';
import tagSelectModal from '#/components/tag/src/tag-select-modal.vue';

import audienceDrawer from './audience-drawer.vue';
import { columns, querySchema } from './data';
import transferModal from './transfer-modal.vue';

interface Props {
  pageType?: string;
}

const props = withDefaults(defineProps<Props>(), {
  pageType: 'all',
});

const userStore = useUserStore();
const userId = computed(() => {
  return userStore.userInfo?.userId;
});

const searchData = ref<Record<string, any>>();
const total = ref(0);
const matchIds = ref<IDS>([]);

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  handleReset: async () => {
    filterApi.clearAllExposed();
    const { formApi, reload } = tableApi;
    await formApi?.resetForm();
    const formValues = formApi.form.values;
    formApi.setLatestSubmissionValues(formValues);
    await reload(formValues);
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: false,
    // 翻页时保留选中状态
    reserve: false,
    // 点击行选中
    // trigger: 'row',
  },
  columns,
  height: 'auto',
  keepSource: false,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        console.log(formValues);
        const values = filterApi.getFormValues();
        filterApi.filterParams(formValues, values);
        // console.log('父组件调用API获取过滤后的高级筛选参数：', formValues);
        const queryData = {
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        };
        if (props.pageType === 'my') {
          queryData.followUpId = userId.value;
        }

        if (matchIds.value.length > 0) {
          queryData.ids = matchIds.value;
        }

        searchData.value = queryData;

        const resp = await employeePage(queryData);
        total.value = resp.total;

        return resp;
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'audience-list-index',
  showOverflow: false,
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    // 需要控制不同的事件 radio也会触发checkbox事件
    checkboxChange: checkBoxEvent,
    checkboxAll: checkBoxEvent,
  },
});

const [AdvancedFilter, filterApi] = useAdvancedFilter({
  tableApi,
});

const [AudienceDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: audienceDrawer,
});

function checkBoxEvent() {
  // const records = tableApi.grid.getCheckboxRecords();
}

function handleAdd() {
  drawerApi.setData({});
  drawerApi.open();
}

async function handleEdit(row: EmployeeVO) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

const router = useRouter();

function handleDetails(row: EmployeeVO) {
  router.push(`/company/audience/details/${row.id}`);
}

// 转移跟进人
const [TransferModal, transferModalApi] = useVbenModal({
  connectedComponent: transferModal,
  destroyOnClose: true,
});

function handleTransfer() {
  const records = tableApi.grid.getCheckboxRecords();
  const ids = records.map((v) => v.id);
  transferModalApi.setData({ ids });
  transferModalApi.open();
}

// 批量加入收藏夹
const [AddEmployeeToFavoriteModal, addEmployeeToFavoriteModalApi] =
  useVbenModal({
    connectedComponent: addEmployeeToFavoriteModal,
    destroyOnClose: true,
  });

function handleFavoriteMenuClick(e: any) {
  const type = e.key;
  if (type === 'check') {
    // 勾选加入
    const records = tableApi.grid.getCheckboxRecords();
    addEmployeeToFavoriteModalApi.setData({
      type,
      records,
      total: records.length,
    });
    addEmployeeToFavoriteModalApi.open();
  }
  if (type === 'search') {
    // 筛选加入
    addEmployeeToFavoriteModalApi.setData({
      type,
      searchData: searchData.value,
      total: total.value,
    });
    addEmployeeToFavoriteModalApi.open();
  }
}

// 批量打标签弹窗
const [TagSelectModal, tagSelectModalApi] = useVbenModal({
  connectedComponent: tagSelectModal,
  destroyOnClose: true,
});

function handleBatchTagOpen() {
  tagSelectModalApi.open();
}

async function handleBatchTagConfirm(data: any) {
  console.log('批量打标签选择确认：', data.ids);
  tagSelectModalApi.lock(true);
  const records = tableApi.grid.getCheckboxRecords();
  const companyIds = records.map((v) => v.id);
  await employeeBatchSetTags({ labelIds: data.ids, ids: companyIds });
  tagSelectModalApi.lock(false);
  tagSelectModalApi.close();
  await tableApi.reload();
}

// 导入
const [ImportModal, importModalApi] = useVbenModal({
  connectedComponent: importModal,
  destroyOnClose: true,
});

function handleImport() {
  importModalApi.setData({});
  importModalApi.open();
}

async function handleImportSuccess() {
  await tableApi.reload();
}

// 匹配
const [EmailMatchModal, emailMatchModalApi] = useVbenModal({
  connectedComponent: importModal,
  destroyOnClose: true,
});
const [MobileMatchModal, mobileMatchModalApi] = useVbenModal({
  connectedComponent: importModal,
  destroyOnClose: true,
});

// 匹配并打标签
const [MatchTagModal, matchTagModalApi] = useVbenModal({
  connectedComponent: importModal,
  destroyOnClose: true,
});

function handleMatchMenuClick(e: any) {
  const type = e.key;
  if (type === 'email') {
    emailMatchModalApi.open();
  }
  if (type === 'mobile') {
    mobileMatchModalApi.open();
  }
  if (type === 'matchTag') {
    matchTagModalApi.open();
  }
}

async function clearMatch() {
  matchIds.value = [];
  await tableApi.reload();
}

function handleMatchSuccess(ids: IDS) {
  if (ids?.length > 0) {
    matchIds.value = ids;
  }
}

function handleMatchTagSuccess() {
  message.success('导入成功，后台已安排打标签任务');
}

const { hasAccessByCodes } = useAccess();
const { onBeforeRouteLeaveCallPage } = useClinkCall();
onMounted(() => {
  if (hasAccessByCodes(['employee:list:trrtCall'])) {
    onBeforeRouteLeaveCallPage();
  }
});
</script>

<template>
  <Page :auto-content-height="true">
    <AdvancedFilter />
    <BasicTable>
      <template #table-title>
        <main-title text="人员总览列表" />
      </template>
      <template #toolbar-actions>
        <Tag v-if="matchIds.length > 0" closable @close="clearMatch">
          关联{{ matchIds.length }}项匹配结果
        </Tag>
      </template>
      <template #toolbar-tools>
        <Space>
          <a-button
            v-access:code="['employee:manager:import']"
            @click="handleImport"
          >
            导入
          </a-button>
          <Dropdown>
            <template #overlay>
              <Menu @click="handleMatchMenuClick">
                <AccessControl :codes="['employee:email:match']" type="code">
                  <MenuItem key="email">邮箱匹配</MenuItem>
                </AccessControl>
                <AccessControl :codes="['employee:mobile:match']" type="code">
                  <MenuItem key="mobile">手机匹配</MenuItem>
                </AccessControl>
                <AccessControl :codes="['employee:tag:match']" type="code">
                  <MenuItem key="matchTag">匹配打标签</MenuItem>
                </AccessControl>
              </Menu>
            </template>
            <a-button
              v-access:code="[
                'employee:email:match',
                'employee:mobile:match',
                'employee:tag:match',
              ]"
            >
              匹配
            </a-button>
          </Dropdown>
          <Tooltip title="将勾选的人员转移给其他跟进人，仅变更跟进人归属">
            <a-button
              v-access:code="['employee:manager:transferFollowUp']"
              :disabled="!vxeCheckboxChecked(tableApi)"
              @click="handleTransfer"
            >
              转移跟进人({{ vxeCheckboxCheckedCount(tableApi) }})
            </a-button>
          </Tooltip>
          <Dropdown>
            <template #overlay>
              <Menu @click="handleFavoriteMenuClick">
                <AccessControl
                  :codes="['employee:favorite:addMember']"
                  type="code"
                >
                  <MenuItem
                    key="check"
                    :disabled="!vxeCheckboxChecked(tableApi)"
                  >
                    按勾选加入({{ vxeCheckboxCheckedCount(tableApi) }})
                  </MenuItem>
                </AccessControl>
                <AccessControl
                  :codes="['employee:favorite:addMemberBySearch']"
                  type="code"
                >
                  <MenuItem key="search" :disabled="total === 0">
                    按当前搜索结果加入({{ total }})
                  </MenuItem>
                </AccessControl>
              </Menu>
            </template>
            <a-button
              v-access:code="[
                'employee:favorite:addMember',
                'employee:favorite:addMemberBySearch',
              ]"
            >
              批量加入收藏夹
            </a-button>
          </Dropdown>
          <Tooltip
            title="批量为勾选的数据添加人员标签，仅新增不会覆盖或删除原有标签"
          >
            <a-button
              v-access:code="['employee:manager:addLabel']"
              :disabled="!vxeCheckboxChecked(tableApi)"
              @click="handleBatchTagOpen"
            >
              批量打标签({{ vxeCheckboxCheckedCount(tableApi) }})
            </a-button>
          </Tooltip>
          <a-button
            type="primary"
            v-access:code="['employee:manager:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
        </Space>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['employee:manager:query']"
            @click="handleDetails(row)"
          >
            {{ $t('pages.common.info') }}
          </ghost-button>
          <ghost-button
            v-access:code="['employee:manager:edit']"
            @click.stop="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <AccessControl :codes="['employee:list:trrtCall']" type="code">
            <Clink :employee-id="row.id" :phone-number="row.mobile" />
          </AccessControl>
        </Space>
      </template>
    </BasicTable>
    <AudienceDrawer @reload="tableApi.reload()" />
    <ImportModal
      :import-api="employeeImport"
      :download-api="employeeDownloadImportTemplate"
      @reload="handleImportSuccess"
    />
    <EmailMatchModal
      :import-api="employeeEmailMatch"
      :download-api="employeeDownloadImportTemplate"
      title="邮箱导入匹配"
      alert-title="模板要求：表格中的「邮箱email」列为必填项"
      alert-type="warning"
      @reload="handleMatchSuccess"
    />
    <MobileMatchModal
      :import-api="employeeMobileMatch"
      :download-api="employeeDownloadImportTemplate"
      title="手机导入匹配"
      alert-title="模板要求：表格中的「手机号mobile」列为必填项"
      alert-type="warning"
      @reload="handleMatchSuccess"
    />
    <MatchTagModal
      :import-api="employeeTagMatch"
      :download-api="employeeDownloadImportTemplate"
      title="导入匹配并打标签"
      enable-tag-match
      alert-title="模板要求：根据您所选的匹配类型，表格中的「邮箱email」或「手机号mobile」列为必填项"
      alert-type="warning"
      @reload="handleMatchTagSuccess"
    />
    <TransferModal @reload="tableApi.reload()" />
    <TagSelectModal
      :tag-type="2"
      :show-op="false"
      :confirmed-close="false"
      @confirm="handleBatchTagConfirm"
    >
      <template #prepend-footer>
        <div class="mr-[10px]">
          已选
          <span class="text-red-500">
            {{ vxeCheckboxCheckedCount(tableApi) }}
          </span>
          条数据
        </div>
      </template>
    </TagSelectModal>
    <AddEmployeeToFavoriteModal
      @reload="tableApi.reload()"
      :add-by-search-api="personalFavoriteAddMemberBySearch"
    />
  </Page>
</template>
